package com.echo.blog.business.elasticsearch.service.impl;

import com.echo.blog.business.elasticsearch.dao.BlogRepository;
import com.echo.blog.business.elasticsearch.model.EsBlog;
import com.echo.blog.business.elasticsearch.service.EsBlogService;
import com.echo.model.utils.ValueUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @version: V1.0
 * @author: chentailai
 * @description: es博客服务层 实现类
 * @className: EsBlogServiceImpl
 * @packageName: EsBlogServiceImpl.java
 * @data: 2020/5/19 16:46
 **/
@Slf4j
@Service
public class EsBlogServiceImpl implements EsBlogService {

    public static final String Indexes = "echoblogs";

    public static final String IndexType = "blog";

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Resource
    private BlogRepository blogRepository;


    @Override
    public List<EsBlog> searchEsBlogList(Integer pageNumber, Integer pageSize, String searchContent) {

        log.info("准备搜索博客简介列表，关键词:{}", searchContent);

        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(searchContent)
                .fuzziness(Fuzziness.ONE);
        Iterable<EsBlog> search = blogRepository.search(builder);
        return Lists.newArrayList(search);
    }

    @Override
    public List<String> getSuggestList(String suggestField, String suggestValue, Integer suggestMaxCount) {
        //构造搜索建议语句,搜索条件字段
        CompletionSuggestionBuilder csBuilder = SuggestBuilders.completionSuggestion(suggestField)
                .prefix(suggestValue, Fuzziness.ONE)
                .size(suggestMaxCount);
        SearchRequestBuilder reqBuilder = elasticsearchTemplate.getClient()
                .prepareSearch(Indexes)
                .setTypes(IndexType);

        SuggestBuilder suggestBuilder = new SuggestBuilder().addSuggestion("my-suggest", csBuilder);
        SearchResponse resSearch = reqBuilder.suggest(suggestBuilder).get();
        CompletionSuggestion completionSuggestion = resSearch.getSuggest().getSuggestion("my-suggest");

        //构造搜索建议数组（去重）
        Set<String> suggestSet = new HashSet<>();
        completionSuggestion.getEntries().forEach(term -> {
            if (!term.getOptions().isEmpty()) {
                term.getOptions().forEach(option -> {
                    String oneTip = ValueUtils.parseString(option.getText());
                    log.info("找到一个搜索建议:{}", oneTip);
                    suggestSet.add(oneTip);
                });
            }

        });
        return new ArrayList<>(suggestSet);
    }
}
